package com.quan.whizenoa.data.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.quan.commons.core.MyBaseServiceImpl;
import com.quan.commons.utils.Pinyin4jHelper;
import com.quan.system.commons.vo.SysUserVo;
import com.quan.system.entity.SysUser;
import com.quan.system.service.SysUserService;
import com.quan.whizenoa.data.entity.OaHrUser;
import com.quan.whizenoa.data.service.OaHrUserService;
import com.quan.hr.entity.HrDept;
import com.quan.hr.entity.HrEmployee;
import com.quan.hr.service.HrDeptService;
import com.quan.hr.service.HrEmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.quan.whizenoa.data.commons.vo.SysDepartVo;
import com.quan.whizenoa.data.entity.SysDepart;
import com.quan.whizenoa.data.mapper.SysDepartMapper;
import com.quan.whizenoa.data.service.SysDepartService;


@Slf4j
@Service
@DS("whizenoa")
public class SysDepartServiceImpl extends MyBaseServiceImpl<SysDepartMapper, SysDepart> implements SysDepartService {

    @Autowired
    private HrDeptService service;


    @Autowired
    private HrEmployeeService employeeService;


    @Autowired
    private OaHrUserService hrUserService;

    @Autowired
    private SysUserService userService;


    /**
     * 数据读取导入
     * 数据库：
     * 部门，员工->部门，员工
     * [whizenoa].sys_depart，[whizenoa].oa_hr_user -> [whizen_pmg_admin].pmg_hr_depart，[whizen_pmg_admin].pmg_hr_employee
     * @return
     */
    @Override
    public List<SysDepartVo> importOaDepartEmp2PmgDepartEmp() {

        // 删除新库所有数据
        this.service.removeByIds(this.service.list());

        // 删除新库所有数据
        this.employeeService.removeByIds(this.employeeService.list());

        // 删除新库所有数据
        this.userService.remove(new QueryWrapper<SysUser>().eq("super_admin", 0));

        final List<SysDepart> list = super.list();
        // 获取一级分类
        final List<SysDepartVo> collect = list.stream()
                .filter(category -> category.getParentId() == null)
                .map(item -> {
                    SysDepartVo bean = new SysDepartVo();
                    BeanUtils.copyProperties(item, bean);

                    log.info("部门：{}, {}", item.getId(), item.getDepartName());

                    HrDept dept = new HrDept();
                    dept.setName(item.getDepartName());
                    dept.setNameEn(item.getDepartNameEn());
                    dept.setNameAbbr(item.getDepartNameAbbr());
                    dept.setDescription(item.getDescription());
                    dept.setCode(item.getOrgCode());
                    dept.setOwnerEmpName(item.getHeader());
                    dept.setMobile(item.getMobile());
                    dept.setFax(item.getFax());
                    dept.setAddress(item.getAddress());

                    this.service.save(dept);

                    QueryWrapper<OaHrUser> queryWrapper = new QueryWrapper<OaHrUser>();
                    queryWrapper.eq("sys_depart_id", item.getId());
                    final List<OaHrUser> emps = this.hrUserService.list(queryWrapper);
                    log.info("部门员工：{}人", emps.size());

                    for (OaHrUser emp : emps) {
                        log.info("员工：{}，{}", emp.getSysWorkNo(), emp.getName());

                        HrEmployee e = new HrEmployee();
                        e.setDeptId(dept.getId());
                        e.setWorkNo(emp.getSysWorkNo());
                        e.setName(emp.getName());
                        e.setSex(emp.getSex());
                        e.setJoinDate(emp.getJoinDate());
                        e.setTelephone(emp.getTelephone());
                        String ws = "0";
                        if(emp.getUserStatus().equals("1")){
                            ws = "2";
                        }
                        if(emp.getUserStatus().equals("2")){
                            ws = "1";
                        }
                        e.setStatus(ws);
                        if(e.getStatus().equals("1")||e.getStatus().equals("2")){
                            e.setQuitDate(LocalDate.now());
                        }
                        e.setSource(emp.getSource());

                        e.setUniversity(emp.getUniversity());
                        e.setMajor(emp.getMajor());
                        e.setEducationLevel(emp.getEducationLevel());
                        e.setGraduatTime(emp.getGraduatTime());
                        e.setJapaneseGrade(emp.getJapaneseGrade());
                        e.setEnglishGrade(emp.getEnglishGrade());
                        e.setIdCardNo(emp.getIdCardNo());
                        e.setNativePlace(emp.getNativePlace());
                        e.setBirthday(emp.getBirthday());
                        String ms = "0";
                        if(emp.getMarriageStatus().equals("1")){
                            ms = "0";
                        }
                        if(emp.getMarriageStatus().equals("2")){
                            ms = "1";
                        }
                        e.setMarriageStatus(ms);
                        e.setDomicilePlace(emp.getDomicilePlace());
                        e.setDomicileProp(emp.getDomicileProp());
                        e.setPhoneNo(emp.getPhoneNo());
                        e.setEmail(emp.getEmail());
                        e.setRemarks(emp.getRemarks());

                        this.employeeService.save(e);


                        // 创建用户
                        SysUserVo u = new SysUserVo();
                        u.setEmpId(e.getId());
                        u.setEmpName(e.getName());
                        u.setUsername(e.getWorkNo());
                        u.setRealname(e.getName());
                        u.setMobile(e.getTelephone());
                        if(null == e.getEmail() || e.getEmail().trim().equals("")){
                            u.setEmail(Pinyin4jHelper.getPinYin(e.getName()) + "@whizen.com");
                        } else {
                            u.setEmail(e.getEmail());
                        }
                        u.setSex(e.getSex());
                        u.setBirthday(e.getBirthday());
                        this.userService.saveUser(u);

                    }

                    // 获取子分类
                    bean.setChildren(getChildrensEmp(bean, list, dept.getId()));

                    return bean;
                }).collect(Collectors.toList());

        return collect;
    }

    //递归查找所有菜单的子菜单
    private List<SysDepart> getChildrensEmp(SysDepartVo root, List<SysDepart> all, Long rootId) {

        List<SysDepart> children = all.stream().filter(categoryEntity -> {
            return null != categoryEntity.getParentId() && categoryEntity.getParentId().equals(root.getId());
        }).map(item -> {
            SysDepartVo bean = new SysDepartVo();
            BeanUtils.copyProperties(item, bean);

            log.info("部门：{}, {}", item.getId(), item.getDepartName());

            HrDept dept = new HrDept();
            dept.setPid(rootId);
            dept.setName(item.getDepartName());
            dept.setNameEn(item.getDepartNameEn());
            dept.setNameAbbr(item.getDepartNameAbbr());
            dept.setDescription(item.getDescription());
            dept.setCode(item.getOrgCode());
            dept.setOwnerEmpName(item.getHeader());
            dept.setMobile(item.getMobile());
            dept.setFax(item.getFax());
            dept.setAddress(item.getAddress());
            this.service.save(dept);

            QueryWrapper<OaHrUser> queryWrapper = new QueryWrapper<OaHrUser>();
            queryWrapper.eq("sys_depart_id", item.getId());
            final List<OaHrUser> emps = this.hrUserService.list(queryWrapper);
            log.info("部门员工：{}人", emps.size());

            for (OaHrUser emp : emps) {
                log.info("员工：{}，{}", emp.getSysWorkNo(), emp.getName());

                HrEmployee e = new HrEmployee();
                e.setDeptId(dept.getId());
                e.setWorkNo(emp.getSysWorkNo());
                e.setName(emp.getName());
                e.setSex(emp.getSex());
                e.setJoinDate(emp.getJoinDate());
                e.setTelephone(emp.getTelephone());
                String ws = "0";
                if(emp.getUserStatus().equals("1")){
                    ws = "2";
                }
                if(emp.getUserStatus().equals("2")){
                    ws = "1";
                }
                e.setStatus(ws);
                if(e.getStatus().equals("1")||e.getStatus().equals("2")){
                    e.setQuitDate(LocalDate.now());
                }
                e.setSource(emp.getSource());

                e.setUniversity(emp.getUniversity());
                e.setMajor(emp.getMajor());
                e.setEducationLevel(emp.getEducationLevel());
                e.setGraduatTime(emp.getGraduatTime());
                e.setJapaneseGrade(emp.getJapaneseGrade());
                e.setEnglishGrade(emp.getEnglishGrade());
                e.setIdCardNo(emp.getIdCardNo());
                e.setNativePlace(emp.getNativePlace());
                e.setBirthday(emp.getBirthday());
                System.out.println(emp.getName()+"=="+emp.getMarriageStatus());
                String ms = "0";
                if(emp.getMarriageStatus().equals("1")){
                    ms = "1";
                }
                if(emp.getMarriageStatus().equals("2")){
                    ms = "0";
                }
                e.setMarriageStatus(ms);
                e.setDomicilePlace(emp.getDomicilePlace());
                e.setDomicileProp(emp.getDomicileProp());
                e.setPhoneNo(emp.getPhoneNo());
                e.setEmail(emp.getEmail());
                e.setRemarks(emp.getRemarks());

                this.employeeService.save(e);

                // 创建用户
                SysUserVo u = new SysUserVo();
                u.setEmpId(e.getId());
                u.setEmpName(e.getName());
                u.setUsername(e.getWorkNo());
                u.setRealname(e.getName());
                u.setMobile(e.getTelephone());

                if(null == e.getEmail() || e.getEmail().trim().equals("")){
                    u.setEmail(Pinyin4jHelper.getPinYin(e.getName()) + "@whizen.com");
                } else {
                    u.setEmail(e.getEmail());
                }
                u.setSex(e.getSex());
                u.setBirthday(e.getBirthday());
                this.userService.saveUser(u);
            }

            //1、找到子菜单(递归)
            bean.setChildren(getChildrensEmp(bean, all, dept.getId()));

            return bean;
        }).collect(Collectors.toList());

        return children;
    }

    /**
     * 数据读取导入
     * 数据库：
     * 部门->部门
     * [whizenoa].sys_depart -> [whizen_pmg_admin].pmg_hr_depart
     * @return
     */
    @Override
    public List<SysDepartVo> importOaDepart2PmgDepart() {

        // 删除新库所有数据
        this.service.removeByIds(this.service.list());

        final List<SysDepart> list = super.list();
        // 获取一级分类
        final List<SysDepartVo> collect = list.stream()
                .filter(category -> category.getParentId() == null)
                .map(item -> {
                    SysDepartVo bean = new SysDepartVo();
                    BeanUtils.copyProperties(item, bean);

                    log.info("部门：{}, {}", item.getId(), item.getDepartName());

                    HrDept dept = new HrDept();
                    dept.setName(item.getDepartName());
                    dept.setNameEn(item.getDepartNameEn());
                    dept.setNameAbbr(item.getDepartNameAbbr());
                    dept.setDescription(item.getDescription());
                    dept.setCode(item.getOrgCode());
                    dept.setOwnerEmpName(item.getHeader());
                    dept.setMobile(item.getMobile());
                    dept.setFax(item.getFax());
                    dept.setAddress(item.getAddress());
                    this.service.save(dept);

                    this.hrUserService.list();

                    // 获取子分类
                    bean.setChildren(getChildrens(bean, list, dept.getId()));

                    return bean;
                }).collect(Collectors.toList());

        return collect;
    }

    //递归查找所有菜单的子菜单
    private List<SysDepart> getChildrens(SysDepartVo root, List<SysDepart> all, Long rootId) {

        List<SysDepart> children = all.stream().filter(categoryEntity -> {
            return null != categoryEntity.getParentId() && categoryEntity.getParentId().equals(root.getId());
        }).map(item -> {
            SysDepartVo bean = new SysDepartVo();
            BeanUtils.copyProperties(item, bean);

            log.info("部门：{}, {}", item.getId(), item.getDepartName());

            HrDept dept = new HrDept();
            dept.setName(item.getDepartName());
            dept.setPid(rootId);
            dept.setName(item.getDepartName());
            dept.setNameEn(item.getDepartNameEn());
            dept.setNameAbbr(item.getDepartNameAbbr());
            dept.setDescription(item.getDescription());
            dept.setCode(item.getOrgCode());
            dept.setOwnerEmpName(item.getHeader());
            dept.setMobile(item.getMobile());
            dept.setFax(item.getFax());
            dept.setAddress(item.getAddress());
            this.service.save(dept);

            //1、找到子菜单(递归)
            bean.setChildren(getChildrens(bean, all, dept.getId()));

            return bean;
        }).collect(Collectors.toList());

        return children;
    }
}